import { useState } from 'react'
import { Table, Divider, Button, message, Modal, Form, Flex, Tag, Input, Select } from 'antd'
import { keepPreviousData, useQuery } from '@tanstack/react-query'
import { ModalForm, ProFormUploadButton } from '@ant-design/pro-components'
import { PlusOutlined, ExclamationCircleFilled, EyeOutlined, UploadOutlined, DownloadOutlined } from '@ant-design/icons'
import { serviceCatalogPage, uploadFiles, exportSysApp, servicePatch, serviceDelete, serviceDeleteId, serviceFlowControl } from '@/api/sharing/serviceCatalog'
import { useNavigate } from 'react-router-dom'
import SearchForm from '../../../components/searchForm'
import BlackWhiteList from './modules/BlackWhiteList'
/* 查询参数 */
const queryItems = [
  {
    name: 'keyword',
    label: '服务名称',
    type: 'INPUT',
  },
  {
    name: 'uri',
    label: '路径',
    type: 'INPUT',
  },
  {
    name: 'label',
    label: '标签',
    type: 'INPUT',
  },
]

/* 文件导出弹窗 */
const UploadModal = () => {
  /* 文件上传操作 */
  const handleImport = (files) => {
    if (files.file.length === 0) {
      message.error('请先选择文件')
      return
    }
    const file = files.file[0]
    return uploadFiles({ file: file.originFileObj })
      .then((response) => {
        if (response.code === 200) {
          message.success('文件上传成功')
          return true
        }
      })
      .catch((error) => {
        message.error('文件上传失败')
      })
  }
  /* 文件上传前操作 */
  const handleBeforeUpload = (file) => {
    const isJson = file.type === 'application/json'
    if (!isJson) {
      message.error('只能上传 JSON 文件!')
    }
    return false // 返回 false 以阻止自动上传
  }

  return (
    <ModalForm style={{ padding: 16 }} trigger={<Button icon={<UploadOutlined />}>导入</Button>} title="导入API" modalProps={{ destroyOnClose: true }} onFinish={handleImport} grid={true} width={400}>
      <ProFormUploadButton
        name="file"
        title="请选择文件上传"
        fieldProps={{
          beforeUpload: handleBeforeUpload,
          multiple: false,
          maxCount: 1,
        }}
      />
    </ModalForm>
  )
}
/* 流量控制弹窗 */
const LimitCountModal = ({ isFormOpen, setIsFormOpen }) => {
  const [form] = Form.useForm()

  /* 流量控制 */
  const handleOk = () => {
    const values = form.getFieldsValue()
    serviceFlowControl(values)
      .then((response) => {
        if (response.code === 200) {
          setIsFormOpen(false)
          message.success('流量控制成功')
          form.resetFields()
        } else {
          message.error('操作失败')
        }
      })
      .catch((error) => {
        console.log('error', error)
      })
  }
  const handleCancel = () => {
    setIsFormOpen(false)
  }
  return (
    <Modal title="流量控制" open={isFormOpen} onOk={handleOk} onCancel={handleCancel}>
      <Form layout="inline" form={form} initialValues={{ type: 'SECONDS', times: '' }}>
        <Form.Item label="服务流量控制" name="type">
          <Select
            style={{ width: '100px' }}
            placeholder="请选择"
            options={[
              { label: '每秒', value: 'SECONDS' },
              { label: '每分钟', value: 'MINUTES' },
              { label: '每小时', value: 'HOURS' },
              { label: '每天', value: 'DAYS' },
            ]}
          />
        </Form.Item>
        <Form.Item
          name="times"
          rules={[
            {
              pattern: /^\d+$/,
              message: '请填入整数字',
            },
          ]}
        >
          <Input placeholder="请填入整数字" />
        </Form.Item>
      </Form>
    </Modal>
  )
}
//i18n
const ServiceCatalogIndex = () => {
  const [queryParam, setQueryParam] = useState({})
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [selectedRows, setSelectedRows] = useState([])
  const [page, setPage] = useState({ pageNo: 1, pageSize: 10 })
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [isFormOpen, setIsFormOpen] = useState(false)
  const [rowId, setRowId] = useState('')
  const navigate = useNavigate()
  const confirm = Modal.confirm

  const columns = [
    {
      dataIndex: 'no',
      title: '序号',
      width: 60,
      align: 'center',
      render(text, _, index) {
        return (page.pageNo - 1) * page.pageSize + index + 1
      },
    },
    {
      dataIndex: 'name',
      title: '服务名称',
      width: 120,
      align: 'center',
      render: (_, record) => {
        return (
          <Button type="link" onClick={() => navigate(`/integration/sharing/serviceCatalog/${record.id}`)}>
            {record.name}
          </Button>
        )
      },
    },
    {
      dataIndex: 'label',
      title: '标签',
      width: 160,
      align: 'center',
      render: (value) => {
        if (!value) return
        return Object.keys(value).map((key) => <Tag key={key}>{`${key}: ${value[key]}`}</Tag>)
      },
    },
    {
      dataIndex: 'uri',
      title: '路径',
      width: 100,
      align: 'center',
    },
    {
      dataIndex: 'status',
      title: '发布状态',
      width: 80,
      align: 'center',
      render: (_, { status }) => {
        return (
          <Tag color={status == '1' ? 'green' : 'geekblue'} key={status}>
            {status == '1' ? '已发布' : '未发布'}
          </Tag>
        )
      },
    },
    {
      dataIndex: 'updateTime',
      title: '更新时间',
      width: 80,
      align: 'center',
    },
    {
      title: '操作',
      key: 'action',
      width: 300,
      align: 'center',
      render: (_, record) => (
        <>
          <Button
            size="small"
            color={record.status == '0' ? 'primary' : 'danger'}
            variant="link"
            onClick={() => {
              handlePublish(record)
            }}
          >
            {record.status == '0' ? '发布' : '下线'}
          </Button>
          <Divider type="vertical" />
          <Button size="small" disabled={record.status == '1'} color="primary" variant="link" onClick={() => navigate(`/integration/sharing/serviceCatalog/${record.id}/edit`)}>
            编辑服务
          </Button>
          <Divider type="vertical" />
          <Button size="small" disabled={record.status == '0'} color="primary" variant="link" onClick={() => navigate(`/integration/sharing/serviceCatalog/${record.id}/tryout`)}>
            服务测试
          </Button>
          <Divider type="vertical" />
          <Button size="small" disabled={record.status == '0'} color="primary" variant="link" onClick={() => setIsFormOpen(true)}>
            流量控制
          </Button>
          <Divider type="vertical" />
          <Button size="small" disabled={record.status == '0'} color="primary" variant="link" onClick={() => handleBlackWhiteList(record)}>
            服务授权
          </Button>
          <Divider type="vertical" />
          <Button size="small" color="danger" variant="link" onClick={() => handleDeleteRow(record)}>
            删除
          </Button>
        </>
      ),
    },
  ]
  const {
    data: tableData,
    isFetching,
    refetch,
  } = useQuery({
    queryKey: ['page-serviceCatalog-serviceCatalogPage', queryParam, page],
    queryFn: () => {
      return serviceCatalogPage({
        pageNo: page.pageNo,
        pageSize: page.pageSize,
        ...queryParam,
      }).then((res) => {
        return res.data
      })
    },
    staleTime: 0,
    placeholderData: keepPreviousData,
  })

  /* 表格选中数据 */
  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys)
    setSelectedRows(selectedRows)
  }
  /* 删除选中数据 */
  const handleDelete = (row) => {
    const ids = row.id || selectedRowKeys
    confirm({
      title: '确认删除所选中数据?',
      icon: <ExclamationCircleFilled />,
      autoFocusButton: null,
      onOk() {
        return serviceDelete(ids).then((res) => {
          onSelectChange([], [])
          refetch()
          message.success('删除成功')
        })
      },
      onCancel() {},
    })
  }
  /* 删除当前行数据 */
  const handleDeleteRow = (row) => {
    const id = row.id
    confirm({
      title: '确认删除数据?',
      icon: <ExclamationCircleFilled />,
      autoFocusButton: null,
      onOk() {
        return serviceDeleteId(id).then((res) => {
          onSelectChange([], [])
          refetch()
          message.success('删除成功')
        })
      },
      onCancel() {},
    })
  }
  /* 发布/下线操作*/
  const handlePublish = (row) => {
    confirm({
      title: row.status == '1' ? '下线API服务' : '发布API服务',
      autoFocusButton: null,
      content: (
        <p>
          API服务发布注册后才可被其他服务或用户访问，进行API编排，确定将<Button type="link">“{row.name}”</Button>服务{row.status == '1' ? '下线' : '发布'}吗？
        </p>
      ),
      onOk() {
        const status = row.status == '1' ? '0' : '1'
        return servicePatch({ id: row.id, status }).then((res) => {
          onSelectChange([], [])
          refetch()
          message.success(row.status == '1' ? '下线成功' : '发布成功')
        })
      },
      onCancel() {},
    })
  }
  /* 文件导出操作 */
  const handleExport = () => {
    confirm({
      title: '是否确认导出?',
      content: '此操作将导出当前条件下所有数据而非选中数据',
      autoFocusButton: null,
      onOk() {
        return exportSysApp({
          ...queryParam,
        }).then((response) => {
          const url = window.URL.createObjectURL(new Blob([response]))
          const a = document.createElement('a')
          a.href = url
          a.download = 'services.json' // 设置下载的文件名
          document.body.appendChild(a)
          a.click()
          a.remove()
          window.URL.revokeObjectURL(url)
          message.success('导出成功')
        })
      },
      onCancel() {
        console.log('cancel')
      },
    })
  }

  /* 服务授权 */
  const handleBlackWhiteList = (row) => {
    setIsModalOpen(true)
    setRowId(row.id)
  }

  return (
    <Flex vertical={true} className="searchTableWrapper">
      <div className="searchTableHeader">服务目录</div>
      <SearchForm
        onSearch={(values) => {
          if (JSON.stringify(values) !== JSON.stringify(queryParam)) {
            setQueryParam({ ...values })
          } else {
            refetch()
          }
        }}
        items={queryItems}
        searchContent="查询"
        buttons={
          <>
            <Button icon={<PlusOutlined />} type="primary" onClick={() => navigate('/integration/sharing/serviceCatalog/add')}>
              新增
            </Button>
            {/* 导入弹窗 */}
            <UploadModal />
            <Button icon={<DownloadOutlined />} onClick={handleExport}>
              导出
            </Button>
            <Button danger disabled={selectedRowKeys.length ? false : true} onClick={handleDelete}>
              批量删除
            </Button>
          </>
        }
      />
      <Table
        rowSelection={{ type: 'checkbox', selectedRowKeys: selectedRowKeys, onChange: onSelectChange }}
        columns={columns}
        rowKey={(record) => record.id}
        loading={isFetching}
        dataSource={tableData?.list || []}
        pagination={{
          current: page.pageNo,
          pageSize: page.pageSize,
          total: tableData?.total,
          onChange: (pageNo, pageSize) => {
            setPage({ pageNo, pageSize })
          },
        }}
      />
      {/* 黑白名单弹窗 */}
      <BlackWhiteList isModalOpen={isModalOpen} setIsModalOpen={setIsModalOpen} id={rowId} />
      {/* 流量控制弹窗 */}
      <LimitCountModal isFormOpen={isFormOpen} setIsFormOpen={setIsFormOpen} />
    </Flex>
  )
}

export default ServiceCatalogIndex
